<template>
  <div>
    <a-modal v-if="type == 1" title="反馈模版管理" :visible="currentVisible" width="600px" @ok="handleSubmit" @cancel="currentVisible = false">
      <a-form-model ref="rulesForm" :model="form" :rules="rules" 
      :labelCol="{ span: 4 }"
      :wrapperCol="{ span: 19 }"
      >
        <a-form-model-item>
          <template v-slot:label>
            <span style="color:red">*</span> 模板
          </template>
          试穿反馈模版
        </a-form-model-item>
        <a-form-model-item>
          <template v-slot:label>
            <span style="color:red">*</span> 反馈项
          </template>
          尺码
        </a-form-model-item>
        <a-form-model-item  style="display: flex;">
          <template v-slot:label>
            <span style="color:red">*</span> 反馈值
          </template>
            <div style="display: flex;flex-wrap:wrap;">
              <a-form-model-item style="width: 27%;margin: 0 10px 10px 0;" v-for="(i, index) in form.feedbackValue"   :prop="`feedbackValue.${index}.valueName`" :rules="rules.valueName" :key="index">
                <a-input v-model="i.valueName" placeholder="请输入" >
                  <a-icon v-if="form.feedbackValue.length > 1" @click="handleDeletValue(index)" slot="suffix" type="close-circle" style="font-size: 20px;cursor: pointer;margin: -30px -20px 0 0;" theme="twoTone" />
                </a-input>
              </a-form-model-item>
              <a v-if="form.feedbackValue.length < 3" @click="handleAddValue">添加反馈值</a>
            </div>
        </a-form-model-item>
        <a-divider />
        <a-form-model-item>
          <template v-slot:label>
            <span style="color:red">*</span> 反馈项
          </template>
          <div style="display: flex;" v-for="(i, index) in form.feedbackItem" :key="index">
            <a-form-model-item style="width: 48%;" :prop="`feedbackItem.${index}.title`" :rules="rules.title" >
              <a-input v-model="i.title" placeholder="请输入" ></a-input>
            </a-form-model-item>
            <a-form-model-item
            style="width: 40%;margin-left: 5px;"
              :labelCol="{ span: 10 }"
              :wrapperCol="{ span: 14 }"
            label="排序" :prop="`feedbackItem.${index}.sort`" :rules="rules.sort">
              <a-input-number placeholder="请输入" v-model="i.sort" :precision="0" :min="0" />
            </a-form-model-item>
            <a @click="handleDeletFeedbackItem(index)">删除</a>
          </div>
        </a-form-model-item>
        <a-divider />
        <a-button type="primary" shape="round" icon="plus" @click="handleAddFeedbackItem">添加反馈项</a-button>
        <div style="margin-top: 15px;">注：文案自动进入 输入框，用户在此基础上编辑</div>
      </a-form-model>
    </a-modal>
    <a-modal v-if="type == 2" title="批量上传" :visible="currentVisible" width="600px" :footer="null" @cancel="currentVisible = false, uploadResponseData = {}">
      <a-form-model ref="rulesForm" :model="form" :rules="rules" 
      :labelCol="{ span: 4 }"
      :wrapperCol="{ span: 19 }"
      >
        <h3 class="title">下载模板，编辑完毕后上传</h3>
        <div class="desc">注：多次上传即新增/覆盖，不做删除操作</div>
        <div class="btn-wrapper">
          <a style="margin-right: 10px;" @click="handleDownloadFeedbackTemplate">下载模板</a>
          <a-upload
            accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            name="file"
            :showUploadList="false"
            :multiple="false"
            :action="uploadUrl"
            @change="handleChange"
          >
          <a-button type="primary" shape="round">上传文件</a-button>
          </a-upload>
        </div>
        <div class="upload-fail-wrapper" v-if="uploadResponseData.success">
          <div class="desc">{{uploadResponseData.date}}日{{uploadResponseData.success}}条上传成功！</div>
          <div class="desc" v-if="uploadResponseData.failure && uploadResponseData.failure != 0">{{uploadResponseData.failure}}条上传失败，<a @click="handleDownloadDerivedResult">下载失败文件</a></div>
        </div>
      </a-form-model>
    </a-modal>
    <a-modal v-if="type == 3" title="编辑" :visible="currentVisible" width="600px" @ok="handleSubmit" @cancel="currentVisible = false">
      <a-form-model ref="rulesForm" :model="form" :rules="rules" 
      :labelCol="{ span: 6 }"
      :wrapperCol="{ span: 17 }"
      >
        <a-form-model-item label="试穿人体重(kg)" prop="weight">
          <a-input-number placeholder="请输入" style="width: 100%;" v-model="form.weight" :precision="0" :min="0" :max="500" allowClear />
        </a-form-model-item>
        <a-form-model-item label="试穿人身高(cm)" prop="height">
          <a-input-number placeholder="请输入" style="width: 100%;" v-model="form.height" :precision="0" :min="0" :max="300" allowClear />
        </a-form-model-item>
        <a-form-model-item label="腰围(cm)">
          <a-input-number placeholder="请输入" style="width: 100%;" v-model="form.waist" :precision="0" :min="0" :max="500" allowClear />
        </a-form-model-item>
        <a-form-model-item label="胸围(cm)">
          <a-input-number placeholder="请输入" style="width: 100%;" v-model="form.chest" :precision="0" :min="0" :max="500" allowClear />
        </a-form-model-item>
        <a-form-model-item label="臀围(cm)">
          <a-input-number placeholder="请输入" style="width: 100%;" v-model="form.hip" :precision="0" :min="0" :max="500" allowClear />
        </a-form-model-item>
        <a-form-model-item label="肩宽(cm)">
          <a-input-number placeholder="请输入" style="width: 100%;" v-model="form.shoulder" :precision="0" :min="0" :max="200" allowClear />
        </a-form-model-item>
        <a-form-model-item label="试穿反馈(尺码)" prop="feedbackResult">
          <a-select v-model="form.feedbackResult" placeholder="请选择" show-search :filter-option="filterOption">
            <a-select-option v-for="(item, index) in feedbackValue" :value="item.valueName" :key="index">{{ item.valueName }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item v-for="(item, index) in form.feedbackItemObj" :label="item.feedbackItemKey" :prop="`feedbackItemObj.${index}.feedbackItemValue`" :rules="rules.feedbackItemValue" :key="index">
          <a-input placeholder="请输入" style="width: 100%;" v-model="item.feedbackItemValue" allowClear />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { feedbackTemplate, feedbackModelImport, derivedResult} from '@/api/micromall/sizeRecommendation'
export default {
  data() {
    return {
      uploadResponseData: {},
      uploadUrl: feedbackModelImport,
      form: {
        feedbackValue: [],
        feedbackItem: []
      },
      rules: {
        valueName: { required: true, message: '请输入', trigger: 'blur' },
        title: { required: true, message: '请输入', trigger: 'blur' },
        sort: { required: true, message: '请输入', trigger: 'blur' },
        weight: { required: true, message: '请输入', trigger: 'blur' },
        height: { required: true, message: '请输入', trigger: 'blur' },
        feedbackResult: { required: true, message: '请输入', trigger: 'blur' },
        feedbackItemValue: { required: true, message: '请输入', trigger: 'blur' }
      }
    }
  },
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: [String, Number],
      default: 1 // 1反馈模版管理 2批量上传 3编辑
    },
    feedbackValue: {
      type: Array,
      default: () => []
    },
    feedbackItem: {
      type: Array,
      default: () => []
    },
    item: {
      type: String,
      default: ''
    }
  },
  watch: {
    type(news){
      if (news == 1) {
        this.$set(this.form, 'feedbackValue', this.feedbackValue)
        this.$set(this.form, 'feedbackItem', this.feedbackItem)
      } else {
        this.form = this.item ? JSON.parse(this.item) : {}
      }
    },
    feedbackValue(news) {
      this.form.feedbackValue = news
    },
    feedbackItem(news){
      this.form.feedbackItem = news
    },
    'item': {
      immediate: true, // 加此属性
      handler() {
        if (this.type != 3) return
        this.form = this.item ? JSON.parse(this.item) : {}
      }
    },
  },
  computed: {
    currentVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  filters: {},
  created() {
    this.form.feedbackValue = this.feedbackValue
    this.form.feedbackItem = this.feedbackItem
    if (this.type == 3) {
      this.form = this.item ? JSON.parse(this.item) : {}
    }
  },
  methods: {
    // 上传
    handleChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        const {msg, message, code, data} = info.file.response
        if (code == 200 ) {
          this.uploadResponseData = data
          this.$emit('onImportChange')
        } else {
          this.$message.error(msg || message)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      }
    },

    // 添加反馈值
    handleAddValue() {
      this.form.feedbackValue.push({valueName: ''})
      console.log(this.form.feedbackValue, 'this.form.feedbackValue')
    },

    // 删除反馈值
    handleDeletValue(index) {
      this.form.feedbackValue.splice(index, 1)
    },

    // 添加反馈项
    handleAddFeedbackItem() {
      this.form.feedbackItem.push({
        title: '',
        sort: ''
      })
    },

    // 删除反馈项
    handleDeletFeedbackItem(index) {
      this.form.feedbackItem.splice(index, 1)
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    // 下载试穿反馈导入模板
    handleDownloadFeedbackTemplate() {
      window.location.href =  feedbackTemplate
    },

    // 下载失败文件
    handleDownloadDerivedResult() {
      window.location.href =  derivedResult
    },

    // 
    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          if (this.type == 1) {
            const sortList = this.form.feedbackItem.map(e => Number(e.sort))
            const sortSet = new Set(sortList)
            if (sortList.length !== sortSet.size) {
              this.$message.info(`反馈项排序值不能相同`)
              return
            }
          }
          this.$emit('onFormChange', this.form)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.title{
  text-align: center;
}
.desc{
  text-align: center;
}
.btn-wrapper{
  margin: 20px 0 10px;
  text-align: center;
}
.upload-fail-wrapper{
  margin-top: 20px;
}
</style>
